package com.websocet.utils;

/**
 * @Author: 陈玉鹏
 * @Description: TODO
 * @DateTime: 2023/7/2 18:02
 */
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.StringUtils;

public class EncryptionUtils {
    private static final String AES = "AES";
    private static final String ENCRYPTION_KEY = "123111111111111111111111"; // 请更换为你自己的密钥

    public static String encrypt(String value) {
        try {
            if (StringUtils.isEmpty(value)) {
                return value;
            }
            SecretKeySpec keySpec = new SecretKeySpec(ENCRYPTION_KEY.getBytes(), AES);
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] encrypted = cipher.doFinal(value.getBytes());
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            throw new RuntimeException("加密失败", e);
        }
    }

    public static String decrypt(String encryptedValue) {
        try {
            if (StringUtils.isEmpty(encryptedValue)) {
                return encryptedValue;
            }
            SecretKeySpec keySpec = new SecretKeySpec(ENCRYPTION_KEY.getBytes(), AES);
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decrypted = cipher.doFinal(Base64.decodeBase64(encryptedValue));
            return new String(decrypted);
        } catch (Exception e) {
            throw new RuntimeException("解密失败", e);
        }
    }
}
